package com.mkj.menu;

import java.awt.*;
import java.awt.event.*;

/**
 * @Author Arrebol
 * @Date 2024/8/4 14:47
 * @Project graphical programming
 * @Description： PopupMenu上下文菜单组件
 */
public class PopupMenuDemo1 {

    Frame frame = new Frame("这里测试PopupMenu上下文菜单组件");
    //创建文本域组件
    TextArea textArea = new TextArea("人生得意需尽欢。", 6, 40);
    //创建Panel容器
    Panel panel = new Panel();
    //创建PopupMenu上下文菜单组件
    PopupMenu popupMenu = new PopupMenu();
    //创建菜单项
    MenuItem comment = new MenuItem("注释");
    MenuItem cancelComment = new MenuItem("取消注释");
    MenuItem copy = new MenuItem("复制");
    MenuItem save = new MenuItem("保存");

    public static void main(String[] args) {
        new PopupMenuDemo1().init();
    }

    public void init() {
        //将多个菜单项放入菜单中
        ActionListener listener = e -> textArea.append("您点击了："+e.getActionCommand()+"\n");
        comment.addActionListener(listener);
        cancelComment.addActionListener(listener);
        copy.addActionListener(listener);
        save.addActionListener(listener);

        popupMenu.add(comment);
        popupMenu.add(cancelComment);
        popupMenu.add(copy);
        popupMenu.add(save);

        panel.add(popupMenu);
        //设置Panel的大小
        panel.setPreferredSize(new Dimension(400,300));
        //为Panel注册鼠标事件，监听用户释放鼠标的动作，届时展示菜单
        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                boolean status = e.isPopupTrigger();
                if(status){
                    //显示PopupMenu
                    popupMenu.show(panel,e.getX(),e.getY());
                }
            }
        });

        //放置文本域和Panel容器
        frame.add(textArea);
        frame.add(panel,BorderLayout.SOUTH);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.pack();
        frame.setVisible(true);
    }
}
